#include "ThreadWaiter.h"


void ThreadWaiter::Append(Thread* pThread)
{
    m_threads.push_back(pThread->Self());
    pThread->SetThreadWaiter(this);
    IncreaseThread();
}

void ThreadWaiter::Remove(Thread* pThread)
{
    delete pThread;
    DecreaseThread();
}

void ThreadWaiter::Wait()
{
    std::list<pthread_t>::iterator it;
    for (it = m_threads.begin(); it != m_threads.end(); /*++it*/)
    {
        pthread_join(*it, NULL);
        it = m_threads.erase(it);
    }
}

void ThreadWaiter::IncreaseThread(int size)
{
    m_mutex.Lock();
    while (m_size >= m_max)
    {
        m_cond.Wait(&m_mutex);
    }
    m_size += size;
    m_mutex.Unlock();
}

void ThreadWaiter::DecreaseThread(int size)
{
    m_mutex.Lock();
    m_size -= size;
    m_cond.Signal();
    m_mutex.Unlock();
}

